import React, { Component } from 'react';
import { Input, Radio, Button, Checkbox, Message } from 'element-react'
import {withRouter} from 'react-router-dom'
import Select from '../base/Select'
import Breadcrumb from '../base/Breadcrumb'
import DatePicker from '../base/DatePicker'
import './discount.css'
class Discount extends Component {
  constructor (props) {
    super (props)
    this.state = {
      label: '新增',
      id: this.props.match.params.id || '',
      platform: [
        {name: 'PC', checked: false},
        {name: 'Android', checked: false},
        {name: 'IOS', checked: false}
      ],
      checkedPlatform: [],
      // 优惠券状态
      typeStatus: 1,
      // 优惠券名称
      couponName: '',
      // 优惠券数量
      createNumber: 0,
      // 优惠券使用下限
      startAmount: null,
      // 有效期开始时间
      startTime: null,
      // 有效期结束时间
      endTime: null,
      // 说明
      couponDescribe: '',
      // 商家
      merchant: '',
      // 用户类型
      userType: '',
      // 适用商品
      goods: '',
      // 商品类型
      goodsType: '',
      // 商品标签
      goodsLabel: '',
      // 折扣或优惠金额
      discountMoney: '',
      discountAmount: null,
      discountRate: null,
      binds: [],
      discountType: null,
      // 优惠类别
      options: [
        {
          label: '打折',
          value: 'discount'
        },
        {
          label: '优惠金额',
          value: 'fullReduction'
        }
      ],
      btnSwitch: true
    }
  }
  // 选择优惠方式
  selectWay (value) {
    this.setState(
      {
        discountType: value
      },
      () => {
        console.log(this.state.discountType)
      }
    )
  }
  // 适用商家
  selectMerchant (event) {
    let value
    if (event) {
      value = event.target.value
    } else {
      value = this.state.merchant
    }
    this.state.binds.map((a, index) => {
      if (a.couponBind === 'shops') {
        this.state.binds[index].couponBindContent = [value]
        this.setState(
          {
            binds: this.state.binds
          },
          () => {
            console.log(this.state.binds)
          }
        )
        this.selectMerchantSet = true
      }
      return a
    })
    console.log(this.selectMerchantSet)
    if (this.selectMerchantSet) return
    this.state.binds.push({
      couponBind: 'shops',
      couponBindContent: [value]
    })
    this.setState(
      {
        binds: this.state.binds
      },
      () => {
        console.log(this.state.binds)
      }
    )
  }
  // 适用用户类型
  selectUser (event) {
    let value
    if (event) {
      value = event.target.value
    } else {
      value = this.state.userType
    }
    this.state.binds.map((a, index) => {
      if (a.couponBind === 'userType') {
        this.state.binds[index].couponBindContent = [value]
        this.setState(
          {
            binds: this.state.binds
          },
          () => {
            console.log(this.state.binds)
          }
        )
        this.selectUserSet = true
      }
      return a
    })
    console.log(this.selectUserSet)
    if (this.selectUserSet) return
    this.state.binds.push({
      couponBind: 'userType',
      couponBindContent: [value]
    })
    this.setState(
      {
        binds: this.state.binds
      },
      () => {
        console.log(this.state.binds)
      }
    )
  }
  // 适用商品
  selectGoods (event) {
    let value
    if (event) {
      value = event.target.value
    } else {
      value = this.state.goods
    }
    this.state.binds.map((a, index) => {
      if (a.couponBind === 'goods') {
        this.state.binds[index].couponBindContent = [value]
        this.setState(
          {
            binds: this.state.binds
          },
          () => {
            console.log(this.state.binds)
          }
        )
        this.state.selectUserSet = true
      }
      return a
    })
    console.log(this.state.selectUserSet)
    if (this.state.selectUserSet) return
    this.state.binds.push({
      couponBind: 'goods',
      couponBindContent: [value]
    })
    this.setState(
      {
        binds: this.state.binds
      },
      () => {
        console.log(this.state.binds)
      }
    )
  }
  // 适用类别
  selectClass (event) {
    let value
    if (event) {
      value = event.target.value
    } else {
      value = this.state.goodsType
    }
    this.state.binds.map((a, index) => {
      if (a.couponBind === 'goodsTypes') {
        this.state.binds[index].couponBindContent = [value]
        this.setState(
          {
            binds: this.state.binds
          },
          () => {
            console.log(this.state.binds)
          }
        )
        this.state.selectUserSet = true
      }
      return a
    })
    console.log(this.state.selectUserSet)
    if (this.state.selectUserSet) return
    this.state.binds.push({
      couponBind: 'goodsTypes',
      couponBindContent: [value]
    })
    this.setState(
      {
        binds: this.state.binds
      },
      () => {
        console.log(this.state.binds)
      }
    )
  }
  // 适用标签
  selectLabel (event) {
    let value
    if (event) {
      value = event.target.value
    } else {
      value = this.state.goodsLabel
    }
    this.state.binds.map((a, index) => {
      if (a.couponBind === 'goodsLabel') {
        this.state.binds[index].couponBindContent = [value]
        this.setState(
          {
            binds: this.state.binds
          },
          () => {
            console.log(this.state.binds)
          }
        )
        this.state.selectLabelSet = true
      }
      return a
    })
    console.log(this.state.selectLabelSet)
    if (this.state.selectLabelSet) return
    this.state.binds.push({
      couponBind: 'goodsLabel',
      couponBindContent: [value]
    })
    this.setState(
      {
        binds: this.state.binds
      },
      () => {
        console.log(this.state.binds)
      }
    )
  }
  // 获取时间
  getTime (start, end) {
    console.log(start + '---' + end)
    this.setState({
      startTime: new Date(start),
      endTime: new Date(end)
    })
  }
  // 提交
  submit () {
    let {binds, couponDescribe, couponName, createNumber, discountAmount, discountRate, discountType, endTime, startAmount, startTime, typeStatus} = this.state
    endTime = new Date(endTime).getTime()
    startTime = new Date(startTime).getTime()
    let data = {binds, couponDescribe, couponName, createNumber, discountAmount, discountRate, discountType, endTime, startAmount, startTime, typeStatus}
    console.log(data)
    if (!binds || !couponDescribe || !couponName || !createNumber || !discountType || !endTime || !startAmount || !typeStatus) {
      Message('请输入完整信息')
      return
    }
    if (!discountRate && !discountAmount) {
      Message('请输入完整信息')
      return
    }
    if (this.state.id) {
      this.$ajax.editDiscountDetail(this.state.id, data).then(res => {
        console.log(res)
        if (res.code === 200) {
          Message({
            type: 'success',
            message: '修改成功!'
          })
          this.props.history.push({
            pathname: '/discountList',
            state: { fromDashboard: true }
          })
        } else {
          Message.error('修改失败')
        }
      }).catch(() => {
        Message.error('网络错误')
      })
      return
    }
    this.$ajax.createDiscount(data).then(res => {
      console.log(res)
      if (res.code === 200) {
        Message({
          type: 'success',
          message: '创建成功!'
        })
        this.props.history.push({
          pathname: '/discountList',
          state: { fromDashboard: true }
        })
      } else {
        Message.error('创建失败')
      }
    }).catch(() => {
      Message.error('网络错误')
    })
  }
  // 取消
  cancel () {
    this.props.history.push({
      pathname: '/discountList',
      state: { fromDashboard: true }
    })
  }
  // 设置优惠金额或优惠折扣
  chooseDiscountMoney (value) {
    if (this.state.discountType === 'discount') {
      if (Number(value) > 1 || Number(value) < 0 || Number(value) == 0) {
        Message.error('请输入0-1的折扣')
        return
      }
      this.setState({
        discountRate: value,
        discountMoney: value,
        discountAmount: null
      })
    } else {
      if (Number(value) < 0) {
        Message.error('请输入正确的金额')
        return
      }
      this.setState({
        discountAmount: value,
        discountMoney: value,
        discountRate: null
      })
    }
  }
  // 优惠券适用平台
  handleCheckedPlatformChange (value) {
    console.log(value)
    this.state.binds.map((a, index) => {
      if (a.couponBind === 'devices') {
        this.state.binds[index].couponBindContent = value
        this.setState(
          {
            binds: this.state.binds
          },
          () => {
            console.log(this.state.binds)
          }
        )
        this.state.selectPlatformSet = true
      }
      return a
    })
    console.log(this.state.selectPlatformSet)
    if (this.state.selectPlatformSet) return
    this.state.binds.push({
      couponBind: 'devices',
      couponBindContent: value
    })
    this.setState(
      {
        binds: this.state.binds
      },
      () => {
        console.log(this.state.binds)
      }
    )
  }
  getDatePicker () {
    if (this.state.id) {
      return (
        <DatePicker getTime={this.getTime.bind(this)} startTime={this.state.startTime} endTime={this.state.endTime} setValue={true}/>
      )
    } else {
      return (
        <DatePicker getTime={this.getTime.bind(this)}/>
      )
    }
  }
  showBtn () {
    if (this.state.btnSwitch) {
      return (
        <div className="btn-group discount-btn-group">
        <Button type="success" size="large" onClick={this.submit.bind(this)}>提交</Button>
        <Button type="warning" size="large" onClick={this.cancel.bind(this)}>取消</Button>
      </div>
      )
    }
  }
  componentWillMount() {
    if (this.props.match.url.match(/discountSee/g)) {
      this.setState({
        btnSwitch: false
      })
    }
    if (this.state.id) {
      this.$ajax.getDiscountDetail([this.state.id]).then(res => {
        if (res.code === 200) {
          let discountMoney, discountAmount, discountRate
          let data = res.data[0]
          let couponName = data.typeName
          let createNumber = data.discountAmount
          let couponDescribe = data.typeDescribe
          let discountType = data.discountType
          if (discountType === 'fullReduction') {
            discountMoney = data.discountAmount
            discountAmount = data.discountAmount
          } else {
            discountMoney = data.discountRate
            discountRate = data.discountRate
          }
          let startAmount = data.startAmount
          let startTime = new Date(Number(data.startTime))
          let endTime = new Date(Number(data.endTime))
          let merchant, userType, goods, goodsType, goodsLabel
          let checkedPlatform = []
          data.binds.forEach(a => {
            if (a.couponBind === 'shops') {
              merchant = a.couponBindContent
            } else if (a.couponBind === 'userType') {
              userType = a.couponBindContent
            } else if (a.couponBind === 'goods') {
              goods = a.couponBindContent
            } else if (a.couponBind === 'goodsTypes') {
              goodsType = a.couponBindContent
            } else if (a.couponBind === 'devices') {
              checkedPlatform.push(a.couponBindContent)
            } else if (a.couponBind === 'goodsLabel') {
              goodsLabel = a.couponBindContent
            }
          })
          let label
          if (this.props.match.url.match(/discountSee/g)) {
            label = '查看'
          } else {
            label = '编辑'
          }
          this.setState({
            checkedPlatform, label, couponName, createNumber, couponDescribe, discountType, startTime, endTime, merchant, userType, goods, goodsType, goodsLabel, discountMoney, discountRate, discountAmount, startAmount
          }, () => {
            console.log(this.state.startTime)
          })
        } else {
        }
      }).then(() => {
        this.selectUser()
        this.selectMerchant()
        this.selectGoods()
        this.selectClass()
        this.selectLabel()
      })
    }
  }
  render() {
    return (
      <div className="discount">
        {/* 优惠券名称 */}
        <Breadcrumb data={['优惠券管理', '优惠券详情', this.state.label]}/>
        <div className="inputGroup">
          <label className="inputLabel">{this.$lang.discountName}：</label>
          <Input placeholder="请输入优惠券名称" className="inputSmall" size="large" onChange={value => {this.setState({couponName: value})}} value={this.state.couponName}/>
        </div>
        {/* 优惠券数量： */}
        <div className="inputGroup">
          <label className="inputLabel">优惠券数量：</label>
          <Input placeholder="请输入优惠券数量" className="inputSmall" size="large" onChange={value => {this.setState({createNumber: value})}} value={this.state.createNumber}/>
        </div>
        {/* 使用金额下限 */}
        <div className="inputGroup">
          <label className="inputLabel">使用金额下限：</label>
          <Input placeholder="请输入使用金额下限（>=0）" className="inputSmall" size="large" onChange={value => {this.setState({startAmount: value})}} value={this.state.startAmount}/>
        </div>
        {/* 适用商家 */}
        <div className="inputGroup">
          <label className="inputLabel">适用商家：</label>
          <Input placeholder="请输入适用商家" className="inputSmall" size="large" onBlur={this.selectMerchant.bind(this)} value={this.state.merchant} onChange={merchant => {this.setState({merchant})}}/>
        </div>
        {/* 适用用户类型 */}
        <div className="inputGroup">
          <label className="inputLabel">适用用户类型：</label>
          <Input placeholder="请输入适用用户类型" className="inputSmall" size="large" onBlur={this.selectUser.bind(this)} onChange={userType => {this.setState({userType})}} value={this.state.userType}/>
        </div>
        {/* 适用商品 */}
        <div className="inputGroup">
          <label className="inputLabel">适用商品：</label>
          <Input placeholder="请输入适用商品" className="inputSmall" size="large" onBlur={this.selectGoods.bind(this)} onChange={goods => {this.setState({goods})}} value={this.state.goods}/>
        </div>
        {/* 适用类别 */}
        <div className="inputGroup">
          <label className="inputLabel">适用类别：</label>
          <Input placeholder="请输入适用类别" className="inputSmall" size="large" onBlur={this.selectClass.bind(this)} onChange={goodsType => {this.setState({goodsType})}} value={this.state.goodsType}/>
        </div>
        {/* 优惠券状态 */}
        <div className="inputGroup">
          <label className="inputLabel">优惠券状态：</label>
          <Radio.Group
            value={this.state.typeStatus}
            onChange={typeStatus => {this.setState({typeStatus})}}>
            <Radio value="1">生效</Radio>
            <Radio value="0">失效</Radio>
          </Radio.Group>
        </div>
        {/* 优惠券有效期 */}
        <div className="inputGroup">
          <label className="inputLabel">优惠券有效期：</label>
          {this.getDatePicker.call(this)}
        </div>
        {/* 优惠券使用平台 */}
        <div className="inputGroup">
          <label className="inputLabel">优惠券使用平台：</label>
          <Checkbox.Group
            value={this.state.checkedPlatform}
            onChange={this.handleCheckedPlatformChange.bind(this)}>
            {
              this.state.platform.map((a, index) =>
                <Checkbox key={index} label={a.name} checked={a.checked}></Checkbox>
              )
            }
          </Checkbox.Group>
        </div>
        {/* 商品标签 */}
        <div className="inputGroup">
          <label className="inputLabel">适用商品标签：</label>
          <Input placeholder="请输入适用商品标签" className="inputSmall" size="large" onBlur={this.selectLabel.bind(this)} onChange={goodsLabel => {this.setState({goodsLabel})}} value={this.state.goodsLabel}/>
          <div className="width20"></div>
        </div>
        {/* 优惠方式 */}
        <div className="inputGroup">
          <label className="inputLabel">优惠方式：</label>
          <Select options={this.state.options} select={this.selectWay.bind(this)} value={this.state.discountType}/>
          <div className="width20"></div>
          <Input placeholder="请输入打折幅度（0 - 1）或优惠金额" className="inputMiddle" size="large" onChange={this.chooseDiscountMoney.bind(this)} value={this.state.discountMoney}/>
        </div>
        {/* 优惠券使用说明 */}
        <div className="inputGroup flexCenterY">
          <label className="inputLabel">优惠券使用说明：</label>
          <Input
            type="textarea"
            autosize={{ minRows: 6, maxRows: 10}}
            placeholder="请输入内容"
            className="inputlarge"
            value={this.state.couponDescribe}
            onChange={(value) => {this.setState({couponDescribe: value}, ()=> {console.log(this.state.couponDescribe)})}}
          />
        </div>
        {this.showBtn.call(this)}
      </div>
    )
  }
}

export default withRouter(Discount)